import { OrderType } from "@/enums"
import { cancelOrder, deleteOrder, followDoctor, getPrescriptionPic } from "@/services/consult"
import { getMedicalOrderDetail } from "@/services/order"
import type { ConsultOrderItem, Doctor, FollowType } from "@/types/consult"
import type { OrderDetail } from "@/types/order"
import { showFailToast, showImagePreview, showSuccessToast } from "vant"
import { onMounted, ref } from "vue"

export const useFollow = (type: FollowType = 'doc') => {
    /* 关注操作 */
const loading = ref(false)
const follow = async (obj: { id: string, likeFlag: 0 | 1 }) => {
    loading.value = true
    try {
        await followDoctor(obj.id, type)
        obj.likeFlag = obj.likeFlag === 1 ? 0 : 1
    } finally {
        loading.value = false
    }
}
    return { loading, follow }
}

export const useShowPrescription = () => {
// 查看处方
    const showPrescription = async (id?: string) => {
    // 判断是否开处方
        if (id) {
        const res = await getPrescriptionPic(id)
        showImagePreview([res.data.url])
     }
     }
    return { showPrescription }
}

// 取消订单
export const useCancelOrder = () => {
  const loading = ref(false)
  const cancelConsultOrder = async (item: ConsultOrderItem) => {
    loading.value = true
    try {
      await cancelOrder(item.id)
      // 修改订单的状态
      item.status = OrderType.ConsultCancel
      item.statusValue = '已取消'
      showSuccessToast('取消成功')
    } catch (e) {
      showFailToast('取消失败')
    } finally {
      loading.value = false
    }
  }
  return { loading, cancelConsultOrder }
}

// 删除订单
export const useDeleteOrder = (cb: (id: string) => void) => {
    const loading = ref(false)
    const deleteConsulOrder = async (item: ConsultOrderItem) => {
        loading.value = true
      try {
        await deleteOrder(item.id)
        // 成功，通知父组件删除这条信息，提示
        showSuccessToast('删除成功')
        cb && cb(item.id)
      } catch (e) {
        showFailToast('删除失败')
      } finally {
        loading.value = false
      }
    }
    return { loading, deleteConsulOrder }
}

// 获取订单详情
export const useOrderDetail = (id: string) => {
  const order = ref<OrderDetail>()
  const loading = ref(false)
  onMounted(async () => {
   loading.value = true
   try {
    const res = await getMedicalOrderDetail(id)
    order.value = res.data
   } finally {
    loading.value = false
   }
})
return { loading, order }
}